package com.prd.component;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.prd.constant.UserConstant;
import com.prd.enums.WxApiTypeEnum;
import com.prd.util.JsonData;
import com.prd.vo.GetWxUserInfoVo;
import com.prd.vo.LoginRegisterVo;
import com.prd.vo.WxUserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @Author lizhaoyi
 * @date 2023/11/18 15:36
 * Description:
 */
@Service
@Slf4j
public class WeChatLoginRegisterStrategy implements LoginRegisterStrategy{


    /**
     * 微信注册登录
     * @param loginRegisterVo
     * @return
     */
    @Override
    public JsonData LoginAndRegister(LoginRegisterVo loginRegisterVo) {
        if (StringUtils.isEmpty(loginRegisterVo.getWxCode())) {
            return JsonData.buildError("微信用户授权临时code不能为空");
        }


        return null;
    }

    public static JsonData toWxLogin(String code){
        //1.通过前端给的code获取openid和access_token
        String getTokenOpenid = StrFormatter.format(WxApiTypeEnum.GET_TOKEN_OPENID.getValue(), UserConstant.APPID,UserConstant.SECRET, code);
        String data = HttpUtil.get(getTokenOpenid);
        log.info("微信获取获取openid和access_token,返回结果======{}=====",data);
        //json=>bean
        GetWxUserInfoVo getWxUserInfoVo = JSONUtil.toBean(data, GetWxUserInfoVo.class);
        //2.通过access_token和openid获取用户信息
        String getUserInfo = StrFormatter.format(WxApiTypeEnum.GET_WX_USERINFO.getValue(), getWxUserInfoVo.getAccess_token(), getWxUserInfoVo.getOpenid());
        String userInfoJson = HttpUtil.get(getUserInfo);
        WxUserInfoVo wxUserInfo = JSONUtil.toBean(userInfoJson, WxUserInfoVo.class);
        log.info("微信获取用户信息===={}====",wxUserInfo);
        if (wxUserInfo == null) {
            return JsonData.buildError("获取微信用户信息异常");
        }
        return JsonData.buildSuccess(wxUserInfo);
    }
}
